#pragma once
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "Log.hpp"
#include <cstring>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Task.hpp"
#include "ThreadPool.hpp"

const int defaultfd = -1;
const std::string defaultip = "0.0.0.0";
const uint16_t defaultport = 8080;
const int backlog = 10;

Log lg;

enum
{
    SOCK_FAIL = 1,
    BIND_FAIL,
    LISTEN_FAIL,
    USAGE_ERR
};

class TcpServer
{
public:
    TcpServer(const std::string &ip = defaultip, const uint16_t port = defaultport)
        : listensock_(defaultfd), ip_(ip), port_(port)
    {
    }
    void Init()
    {
        listensock_ = socket(AF_INET, SOCK_STREAM, 0);
        if (listensock_ < 0)
        {
            lg(Fatal, "listensock create fail, errno: %d, because %s", errno, strerror(errno));
            exit(SOCK_FAIL);
        }
        lg(Info, "listensock create success");

        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        inet_aton(ip_.c_str(), &(local.sin_addr));

        if (bind(listensock_, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind fail, errno: %d, because %s", errno, strerror(errno));
            exit(BIND_FAIL);
        }
        lg(Info, "bind success, errno: %d, because %s", errno, strerror(errno));

        if (listen(listensock_, backlog) < 0)
        {
            lg(Fatal, "listen fail, errno: %d, because %s", errno, strerror(errno));
            exit(LISTEN_FAIL);
        }
        lg(Info, "listen success, errno: %d, because %s", errno, strerror(errno));
    }

    void Run()
    {
        ThreadPool<Task>::GetInstance()->Start();
        lg(Info, "TcpServer is running...");
        std::cout << "服务器开始运行" << std::endl;
        while (true)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            int sockfd = accept(listensock_, (struct sockaddr *)&client, &len);
            if (sockfd < 0)
            {
                lg(Warning, "accept fail, errno: %d, because %s", errno, strerror(errno));
                continue;
            }
            std::cout << "服务器获取到链接" << std::endl;
            uint16_t clientport = ntohs(client.sin_port);
            char clientip[32];
            inet_ntop(AF_INET, &(client.sin_addr), clientip, sizeof(clientip));

            lg(Info, "get a new link..., sockfd: %d, client ip: %s, client port: %d", listensock_, clientip, clientport);

            Task t(sockfd, clientip, clientport);
            ThreadPool<Task>::GetInstance()->Push(t); 
        }
    }
    ~TcpServer()
    {
    }

private:
    int listensock_;
    std::string ip_;
    uint16_t port_;
};